package login

import (
	"d-serv-go/server/core/bean"
	"d-serv-go/server/core/conf"
	"d-serv-go/server/core/consts"
	"d-serv-go/server/core/db"
	"d-serv-go/server/core/util/encrypt"
	"errors"
	"fmt"
	"strconv"
	"strings"
)

const (
	PARAM_ID        = "id"
	PARAM_LOGINNAME = "loginName"
	PARAM_PASSWORD  = "password"
	PARAM_CMPYCODE  = "cmpyCode"
)

type PasswordModule struct {
}

func (p *PasswordModule) authenticate(paramBean *db.ParamBean) (*db.UserBean, error) {
	context := db.Ctx()
	var cmpyCode string
	// 接受的参数：id,password 或者 loginName,password,cmpyCode
	// id := paramBean.GetStr(PARAM_ID)
	password := paramBean.GetStr(PARAM_PASSWORD)
	loginName := paramBean.GetStr(PARAM_LOGINNAME)
	cmpyCode = paramBean.GetStr(PARAM_CMPYCODE)
	if len(loginName) == 0 || len(password) == 0 || len(cmpyCode) == 0 {
		return nil, errors.New("认证参数错误，用户名：" + loginName + ";公司编码：" + cmpyCode + ";密码长度：" + strconv.Itoa(len(password)))
	}

	if context.GetBool("SY_LOGIN_NAME_LOWERCASE", true) {
		loginName = strings.ToLower(loginName)
	}
	userBean, err := db.UserMgr.GetUserByLoginName(loginName, cmpyCode)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("authenticate, error:%v", err))
	}
	// 验证用户是否已被锁定
	if userBean.GetInt("USER_STATE") == 4 {
		return nil, errors.New("账户已锁定,请重置密码。")
	}

	// 验证公司信息
	cmpy := db.DictMgr.GetItem("SY_ORG_CMPY", cmpyCode)
	if cmpy == nil {
		return nil, errors.New(context.GetSyMsg("SY_CMPY_NOT_FOUND", cmpyCode))
	} else if cmpy.GetInt("FLAG") != consts.YES_INT { // 公司被禁用
		return nil, errors.New(context.GetSyMsg("SY_CMPY_FORBIDDEN", cmpyCode))
	}

	// 加密后进行判断
	password = encrypt.EncryptUtil.Encrypt(password, context.GetStr("SY_USER_PASSWORD_ENCRYPT", encrypt.MD5))
	if password == userBean.GetPassword() { // 登录成功
		// 登录成功,登录清空计数
		// LoginUtil.removeUserLoginFails(userBean.getStr("USER_CODE"));
	} else { // 登录失败
		if conf.ConfMgr.GetBool("SY_LOGIN_FAIL_COUNT", true) {
			// 根据策略判断用户是否需要被锁定
			// LoginUtil.checkMessageByPolicy(userBean);
		}
		return nil, errors.New("输入的密码错误。")
	}
	return userBean, nil
}

func (p *PasswordModule) Login(paramBean *db.ParamBean) *bean.OutBean {
	out := bean.NewOutBean()
	context := db.Ctx()
	userBean, err := p.authenticate(paramBean);
	if err != nil {
		out.SetError(fmt.Sprintf("login error:%v", err))
	} else {
		enableInvalideUserCanotLogin := conf.ConfMgr.GetBool("SY_ENABLE_INVALID_USER_NOT_LOGIN", false);
		if (enableInvalideUserCanotLogin && !userBean.IsActivity()) {
			out.SetError("该用户无效，请联系系统管理员，用户状态是否处于删除，离职，退休等状态。")
		} else{
			//设用在线用户信息
			userState := context.SetOnlineUser(userBean);
			out.SetId(userState.GetId());
			out.Set("USER_CODE", userState.GetStr("USER_CODE"));
			out.Set("USER_TOKEN", userState.GetStr("USER_TOKEN"));
			if (userState.GetBool("USER_FIRST_LOGIN")) { //首次登录标志
				out.Set("USER_FIRST_LOGIN", true);
			}
		}
	}
	out.SetOk("")
	return out
}
